import Vue from 'vue'
import VueRouter from 'vue-router'
import App from '../App.vue'
import Main from '../view/main.vue'
Vue.use(VueRouter)

const routes = [{
  path: '/',
  component: App,
  children: [
    {
      path: '',
      name: 'Main',
      component: Main,
    },
    {
      path: '/subPath/:subPath',
      name: 'subPath',
      component: () => import('../view/subsystem.vue'),
    }
  ]
},
{
  path: '/login',
  name: 'login',
  component: () => import('../components/loginOrRegister/login.vue')
},
{
  path: '/register',
  name: 'register',
  component: () => import('../components/loginOrRegister/register.vue')
},
{
  path: '/userManage',
  name: 'userManage',
  component: () => import('../view/userManage/index.vue'),
  children: [{
    path: 'personalMsg',
    name: 'personalMsg',
    component: () => import('../view/userManage/personalMsg.vue')
  },
  {
    path: 'usersMsg',
    name: 'usersMsg',
    component: () => import('../view/userManage/userMsg.vue')
  },
  {
    path: 'dataSourceMsg',
    name: 'dataSourceMsg',
    component: () => import('../view/userManage/dataSourceMsg.vue')
  },
  ]
},
{
  path: "/addPanel/subPath/:subPath/chart",
  name: 'addPanel',
  component: () => import('../view/panel/index.vue'),
  children: [{
    path: 'table',
    name: "table",
    component: () => import('../view/chart/table.vue')
  },
  {
    path: 'scrolltable',
    name: "scrolltable",
    component: () => import('../view/chart/scrolltable.vue')
  },
  {
    path: "line",
    name: "line",
    component: () => import('../view/chart/line.vue')
  },
  {
    path: "bar",
    name: "bar",
    component: () => import('../view/chart/bar.vue')
  },
  {
    path: "pie",
    name: "pie",
    component: () => import('../view/chart/pie.vue')
  },
  {
    path: "gauge",
    name: "gauge",
    component: () => import('../view/chart/gauge.vue')
  },
  {
    path: "sum",
    name: "sum",
    component: () => import('../view/chart/sum.vue')
  },
  ]
},
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
router.beforeEach((to, from, next) => {
  let isAuthenticated = localStorage.getItem('token') ? localStorage.getItem('token') : '';
  if (to.name === 'register') next();
  else if (to.name !== 'login' && !isAuthenticated) next({
    name: 'login'
  })
  else next();
})
export default router